<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
         <el-breadcrumb-item :to="{ path: '/roles' }">首页</el-breadcrumb-item>
         <el-breadcrumb-item>活动管理</el-breadcrumb-item>
         <el-breadcrumb-item>活动列表</el-breadcrumb-item>
         <el-breadcrumb-item>活动详情</el-breadcrumb-item>
       </el-breadcrumb>
       <el-card :body-style="{ padding: '10px'}">
           <el-row>
               <el-col :span="4">
                   <el-button type="primary" @click="addroleVisible=true"> 添加角色</el-button>
               </el-col>
           </el-row>
           <el-table border :data='rolelist'>
               <!-- 展开列 -->
               <el-table-column type="expand" width="50">
                   <template slot-scope="scope">
                        <el-row v-for="(item,i1) in scope.row.children" :key="item.id" :class="className(i1)" class="flexLay">
                        <!--一级权限-->
                          <el-col :span="5" >
                              <el-tag   closable type="success" @close='deleteRight(scope.row,item.id)'>
                                  {{item.authName}} 
                               </el-tag>
                               <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!--二三级权限-->
                            <el-col :span="19" >
                                <el-row v-for='(item2,i2) in item.children' :key=item2.id :class="i2==0?'':'topborder'">
                                    <el-col :span="5">
                                        <el-tag  closable type="info" @close='deleteRight(scope.row,item2.id)'>
                                          {{item2.authName}} 
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="15">
                                        <el-tag  closable type="warning" v-for='(item3) in item2.children' :key='item3.id' @close='deleteRight(scope.row,item3.id)'>
                                          {{item3.authName}} 
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>   
                        </el-row>
                   </template>
               </el-table-column>
               <el-table-column type="index" label='#' width="50"></el-table-column>
               <el-table-column label='角色名称' prop='roleName' align='center'></el-table-column>
               <el-table-column label='角色描述' prop='roleDesc' align='center'></el-table-column>
               <el-table-column label='操作' width='400'>
                   <template slot-scope="scope">
                       <el-button type="primary" icon="el-icon-edit" size='mini' @click="editRole(scope.row.id)">编辑</el-button>
                       <el-button type="danger" icon="el-icon-delete" size='mini' @click="deleteRole(scope.row.id)">删除</el-button>
                       <el-button type="primary" icon="el-icon-setting" size='mini' @click='setRight(scope.row)'>分配权限</el-button>
                   </template>
               </el-table-column>
           </el-table>
           <!--增加角色表单-->
           <el-dialog title="增加角色" :visible.sync="addroleVisible" @close='resetForm' >
            <el-form :model="addRole" label-width="80px" label-position='left' :rules="rules" ref="roleform"  :hide-required-asterisk='false'>
               <el-form-item label="角色名称" prop='roleName'>
                  <el-input v-model="addRole.roleName" autocomplete="off"></el-input>
               </el-form-item>
               <el-form-item label="角色描述" prop='roleDesc'>
                  <el-input v-model="addRole.roleDesc" autocomplete="off"></el-input>
               </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
               <el-button @click="addroleVisible = false">取 消</el-button>
               <el-button type="primary" @click="addrole">确 定</el-button>
            </div>
           </el-dialog>  
           <!--编辑角色表单--> 
           <el-dialog title="修改角色信息" :visible.sync="editFormVisible" >
            <el-form :model="editroleForm" label-width="80px" label-position='left' :rules="rules" ref="ruleForm2" :hide-required-asterisk='false'>
               <el-form-item label="角色名称" >
                  <el-input v-model="editroleForm.roleName" autocomplete="off" disabled></el-input>
               </el-form-item>
               <el-form-item label="角色描述" prop='roleDesc' >
                  <el-input v-model="editroleForm.roleDesc" autocomplete="off"></el-input>
               </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
               <el-button @click="editFormVisible = false">取 消</el-button>
               <el-button type="primary" @click="editrolePut">确 定</el-button>
            </div>
           </el-dialog>
           <!--分配权限-->
           <el-dialog title="分配用户权限" :visible.sync="setRightVisible" @close='closeRightVisible'>
               <el-tree :data="rightlist" :props="rightProps"  show-checkbox :highlight-current='true'
               :default-expand-all='true' :default-checked-keys='defaultRight' node-key='id' ref='tree'>
               <!--:data="rightlist"绑定的数据  :props="rightProps"要显示的数据 :default-expand-all='true'默认全部展开 :default-checked-keys='defaultRight' 默认选中的节点-->
               </el-tree>
               <div slot="footer" class="dialog-footer">
                  <el-button @click="setRightVisible = false">取 消</el-button>
                  <el-button type="primary" @click="setRightPut">确 定</el-button>
               </div>
           </el-dialog>
            <!--页码导航-->
          <div class="block">
               <el-pagination @size-change="handleSizeChange"  @current-change="handleCurrentChange"
               :current-page="queryInfo.pagenum" :page-sizes="[5,10,20]" :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="this.rolelist.length">
               </el-pagination>
             </div>
       </el-card>
    </div>

</template>
<script>
export default {
    created(){
        this.getRolelist()
    },
    data(){
        return {
            //角色列表
            rolelist:[],
            //权限列表
            rightlist:[],
            //增加角色数据
            addRole:{
                roleName:'',
                roleDesc:''
            },
            rules:{
                roleName: [
                 { required: true, message: '请输入角色名称', trigger: 'blur' }
                ],
                roleDesc: [
                 { required: true, message: '请输入角色描述', trigger: 'blur' }
                ],
            },
            addroleVisible:false,
            editFormVisible:false,
            editroleForm:'',
            //设置查找请求的数据
            queryInfo:{
                query:'',//查询条件
                pagenum:1,//第几页
                pagesize:5//每页显示的条数
            },
            //设置权限
            setRightVisible:false,
            rightProps:{
                label:'authName',
                children:'children'
            },
            defaultRight:[],
            roleId:''
        }
    },
    methods:{
        //发送获得角色列表请求
        async getRolelist(){
            const {data:res}=await this.$http.get('roles')
            if(res.meta.status!=200) return this.$message.error('获取信息失败')
            this.rolelist=res.data  
        },
        //重置表单
        resetForm(){
           this.$refs.roleform.resetFields()
        },
        //发送添加角色请求
        addrole(){
            this.$refs.roleform.validate(async (valid) => { 
                if(!valid) return this.$message.error('数据填写有误')
                const {data:res}=await this.$http.post('roles',this.addRole)
                if(res.meta.status!=201) return this.$message.error("角色添加失败")
                addroleVisible = false
                this.getRolelist()
                })
        },
        //删除用户
        async deleteRole(id) {
            const result=await this.$confirm('你将要删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).catch((err) =>err )
           if(result=='confirm'){
              const {data:res}=await this.$http.delete(`roles/${id}`)
              if(res.meta.status!=200) return this.$message.error('删除用户失败')
              this.$message.success('删除用户成功')
            //   this.queryInfo.pagenum=Math.floor(this.total/this.queryInfo.pagesize)
              this.getRolelist()
           }
      },
      //编辑角色
      editrolePut(){
         this.$refs.ruleForm2.validate(async valid=>{
              if(!valid) return this.$message.error('数据有误')
              const {data:res}=await this.$http.put(`roles/${this.editroleForm.roleId}`,{
                  roleName:this.editroleForm.roleName,
                  roleDesc:this.editroleForm.roleDesc
              })
              if(res.meta.status!=200) return this.$message.error('修改数据失败')
              this.editFormVisible=false
              this.getRolelist()
         })
      },
      async editRole(id){
         this.editFormVisible = true
         const {data:res}=await this.$http.get(`roles/${id}`)
         if(res.meta.status!=200) return this.$message.error('获取数据失败')
         this.editroleForm=res.data
      },
        //修改每页显示条数
        handleSizeChange(val){
           this.queryInfo.pagesize=val;
           this.getRolelist()
        },
        //显示当前页数的信息
        handleCurrentChange(val){
           this.queryInfo.pagenum=val
           this.getRolelist()
        },
        className(i1){
            if(i1==0) return 'topborder botborder'
            else return 'botborder'
        },
        //删除用户权限
        async deleteRight(role,rightid){
            const result=await this.$confirm('你将要删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).catch((err) =>err )
           if(result=='confirm'){
              const {data:res}=await this.$http.delete(`roles/${role.id}/rights/${rightid}`)
              if(res.meta.status!=200) return this.$message.error('删除用户失败')
              this.$message.success('删除权限成功')
              role.children=res.data
           }
        },
        //分配用户权限
        async setRight(role){
           //获取权限列表
           const {data:res}=await this.$http.get('rights/tree')
           if(res.meta.status!=200) return this.$message.error('获取数据失败')
           this.rightlist=res.data
           this.getDefaulRightList(role,this.defaultRight)
           this.setRightVisible=true
           this.roleId=role.id
        },
            //获取到选中的三级节点 递归函数
        getDefaulRightList(node,arr){
            if(!node.children){
              return arr.push(node.id)
            }
            node.children.forEach(item=>{
               this.getDefaulRightList(item,arr)
            })    
        },
        async setRightPut(){
            //获得选中和半选中的节点id
            const ckeckedKeys=[...this.$refs.tree.getCheckedKeys(),...this.$refs.tree.getHalfCheckedKeys()]
            const keysStr=ckeckedKeys.join(',')
            //提交请求
            const {data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:keysStr})
            if(res.meta.status!=200) return this.$message.error('设置权限失败')
            this.setRightVisible=false
            this.getRolelist()
            
        },
        //关闭窗口 重置默认选中的节点 和选中的角色
        closeRightVisible(){
            this.defaultRight=[]
            this.roleId=''
        }
}
}
</script>
<style lang="less" scoped>
    .el-col{
        padding: 2px;
    }
     .topborder{
         border-top: 1px solid grey;
     }
     .botborder{
         border-bottom: 1px solid grey;
     }
     .flexLay{
         display: flex;
         align-items: center;
     }
     .el-tag{
         margin-left: 5px;
     }
</style>